package com.qubuyer.business.auth.view

import android.os.Bundle
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.core.widget.doAfterTextChanged
import com.blankj.utilcode.util.ActivityUtils
import com.qubuyer.R
import com.qubuyer.business.main.MainActivity
import com.qubuyer.business.auth.viewmodel.RegisterViewModel
import com.qubuyer.constant.AppConstant
import com.qubuyer.constant.NetConstant
import com.qubuyer.core.app.MVVMActivity
import com.qubuyer.core.utils.ActivityManager
import com.qubuyer.customview.BrowserActivity
import com.qubuyer.databinding.ActivityRegisterBinding
import com.qubuyer.utils.StatusBarUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

class RegisterActivity : MVVMActivity<ActivityRegisterBinding, RegisterViewModel>() {

    override val viewModel: RegisterViewModel by injectVMByActivity()

    override fun onDataBind(dataBinding: ActivityRegisterBinding) {
        dataBinding.host = this
    }

    override val layoutId: Int
        get() = R.layout.activity_register
    private var mScanInviteCode: String? = null
    private var inCountDown = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (null != intent && null != intent.getSerializableExtra(AppConstant.INTENT_EXTRA_KEY)) {
            mScanInviteCode = intent.getSerializableExtra(AppConstant.INTENT_EXTRA_KEY) as String?
        }
        val layoutParams = dataBinding.ivBack.layoutParams as ViewGroup.MarginLayoutParams
        layoutParams.topMargin += StatusBarUtil.getStatusBarHeight()
        dataBinding.ivBack.layoutParams = layoutParams
        StatusBarUtil.setStatusBarLightMode(this, true)
        dataBinding.etMobile.doAfterTextChanged {
            dataBinding.ivDelMobile.isVisible = !it.isNullOrEmpty()
            checkInput()
            if (!inCountDown) {
                dataBinding.tvGetCode.isEnabled = it?.length == 11
            }
        }
        dataBinding.etCode.doAfterTextChanged {
            dataBinding.ivDelCode.isVisible = !it.isNullOrEmpty()
            checkInput()
        }
        dataBinding.etPwd.doAfterTextChanged {
            dataBinding.ivDelPwd.isVisible = !it.isNullOrEmpty()
            checkInput()
        }
        if (!TextUtils.isEmpty(mScanInviteCode)) {
            dataBinding.etInviteCode.setText(mScanInviteCode)
            dataBinding.etInviteCode.isEnabled = false
        } else {
            dataBinding.etInviteCode.doAfterTextChanged {
                dataBinding.ivDelInviteCode.isVisible = !it.isNullOrEmpty()
                checkInput()
            }
        }
        viewModel.getCodeResult.observe(this, {
            if (it) {
                toast("验证码获取成功")
                dataBinding.tvGetCode.isEnabled = false
                launch {
                    (60 downTo 0).asFlow().onEach { index ->
                        inCountDown = true
                        dataBinding.tvGetCode.text = "重新获取${index}S"
                        delay(1000)
                    }.collectLatest {
                        inCountDown = false
                        dataBinding.tvGetCode.text = "获取验证码"
                        dataBinding.tvGetCode.isEnabled = false
                    }
                }
            }
        })
        viewModel.thirdPartLoginResult.observe(this, {
            when (it) {
                200 -> ActivityManager.finishExcept(MainActivity::class.java)
            }
        })
    }


    fun onClick(v: View) {
        when (v.id) {
            R.id.ivBack -> finish()
            R.id.ivDelCode -> dataBinding.etCode.setText("")
            R.id.ivDelMobile -> dataBinding.etMobile.setText("")
            R.id.ivDelPwd -> dataBinding.etPwd.setText("")
            R.id.ivDelInviteCode -> dataBinding.etInviteCode.setText("")
            R.id.tvGetCode -> {
                viewModel.getCode(dataBinding.etMobile.text.toString())
            }
            R.id.ivPassVisible -> {
                dataBinding.ivPassVisible.isSelected = !dataBinding.ivPassVisible.isSelected
                if (dataBinding.ivPassVisible.isSelected) {
                    dataBinding.etPwd.transformationMethod = HideReturnsTransformationMethod.getInstance()
                } else {
                    dataBinding.etPwd.transformationMethod = PasswordTransformationMethod.getInstance()
                }
                dataBinding.etPwd.setSelection(dataBinding.etPwd.length())
            }
            R.id.tvAgreement -> {
                startActivity(BrowserActivity::class.java) {
                    it.putExtra(BrowserActivity.KEY_URL, NetConstant.BASE_URL + "/home/html/helpCenterDetail?id=43")
                }
            }
            R.id.tvRegister -> {
                val phone = dataBinding.etMobile.text.toString()
                val code = dataBinding.etCode.text.toString()
                val pwd = dataBinding.etPwd.text.toString()
                val inviteCode = dataBinding.etInviteCode.text.toString()
                viewModel.register(phone, pwd, code, if (!TextUtils.isEmpty(mScanInviteCode)) mScanInviteCode!! else inviteCode)
            }
        }
    }

    private fun checkInput() {
        dataBinding.tvRegister.isEnabled = dataBinding.etMobile.length() == 11 &&
                dataBinding.etCode.length() == 6 &&
                dataBinding.etPwd.length() >= 3 &&
                dataBinding.etInviteCode.length() > 0
    }
}